import httplib, urllib, base64, datetime, json
class APIConnection:
    param_dist = {
        'model':'latest',
        'count':'10000',
        'offsest':'0',
        'attributes': 'Id,AA.AuId,AA.AfId,RId,F.FId,C.CId,J.JId',
        'subscription-key':'f7cc29509a8443c5b3a5e56b0e38b5a6',
    }
    
    
    
    def GetEntityById(self,ID):
        query = "Id="+str(ID)
        self.param_dist['expr'] = query

        # Change to params
        params = urllib.urlencode(self.param_dist)

        # Search from API
        try:
            conn = httplib.HTTPSConnection('oxfordhk.azure-api.net')
            conn.request("GET", "/academic/v1.0/evaluate?%s" % params)#, "{body}", headers)
            response = conn.getresponse()
            data = response.read()
            # Change from JSON
            jp = json.loads(data)
            # conn.close()
            return jp['entities'][0]
        except Exception as e:
            print("[Errno {0}] {1}".format(e.args[0], e.message))
        finally:
            conn.close()
            
    def GetEntityByAuId(self,AuId):
        query = "Composite(AA.AuId="+str(AuId)+")"
        self.param_dist['expr'] = query

        # Change to params
        params = urllib.urlencode(self.param_dist)

        # Search from API
        try:
            conn = httplib.HTTPSConnection('oxfordhk.azure-api.net')
            conn.request("GET", "/academic/v1.0/evaluate?%s" % params)#, "{body}", headers)
            response = conn.getresponse()
            data = response.read()
            # Change from JSON
            jp = json.loads(data)
            # conn.close()
            return jp['entities']
        except Exception as e:
            print("[Errno {0}] {1}".format(e.errno, e.strerror))
        finally:
            conn.close()

    def GetEntityByQuery(self,query,attributes=None):
        self.param_dist['expr'] = query
        
        if(attributes is not None):
            self.param_dist['attributes'] = attributes
        
        # Change to params
        params = urllib.urlencode(self.param_dist)

        # Search from API
        try:
            conn = httplib.HTTPSConnection('oxfordhk.azure-api.net')
            conn.request("GET", "/academic/v1.0/evaluate?%s" % params)#, "{body}", headers)
            response = conn.getresponse()
            data = response.read()
            # Change from JSON
            jp = json.loads(data)
            # conn.close()
            return time,jp['entities']
        except Exception as e:
            print("[Errno {0}] {1}".format(e.args[0], e.message))
        finally:
            conn.close()
                 
